﻿using LEE.AspNetCore.Extensions.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog;
using System.Threading.Tasks;

namespace LEE.AspNetCore.Extensions.Attributes
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobleExceptionAttribute : ExceptionFilterAttribute
    {
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            var exception = context.Exception.GetBaseException();
            var errorMessage = exception.Message;
            context.ExceptionHandled = true;

            var result = new ApiResult
            {
                Success = false,
                Code = 500,
                Message = errorMessage
            };

            if (exception is CustomException customException)
            {
                result.Code = customException.HttpStatusCode;
            }
            else
            {
                var request = (ControllerActionDescriptor)context.ActionDescriptor;
                Log.Error(exception, $"{request.ActionName}/{request.ControllerName},errorMessage:{errorMessage}");
            }
            context.Result = new JsonResult(result);
            context.HttpContext.Response.StatusCode = 200;
            return base.OnExceptionAsync(context);
        }
    }
}
